package com.zqh.forum.services.impl;

import com.zqh.forum.common.AppResult;
import com.zqh.forum.common.ResultCode;
import com.zqh.forum.dao.UserMapper;
import com.zqh.forum.exception.ApplicationException;
import com.zqh.forum.model.Board;
import com.zqh.forum.model.User;
import com.zqh.forum.services.IUserService;
import com.zqh.forum.utils.MD5Util;
import com.zqh.forum.utils.StringUtil;
import com.zqh.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        //1.非空校验
        if(user == null ||
                !StringUtils.hasLength(user.getUsername()) ||
                !StringUtils.hasLength(user.getNickname()) ||
                !StringUtils.hasLength(user.getPassword()) ||
                !StringUtils.hasLength(user.getSalt())){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.按照用户名查询用户信息
        User existsUser = userMapper.selectByUserName(user.getUsername());
        //2.1判断用户是否存在
        if(existsUser != null){
            //用户存在
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        //3.新增用户-设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        //创建当前日期
        Date date = new Date();
        user.setUpdateTime(date);
        user.setCreateTime(date);

        //将数据插入到数据库中
        int row = userMapper.insertSelective(user); //此处的返回值是受影响的行数
        if(row != 1){
            //未插入成功
            //打印日志
            log.info(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED.FAILED_CREATE));
        }
        //插入成功
//        log.info(ResultCode.SUCCESS.toString());
        log.info("新增用户成功：username = " + user.getUsername() + ".");
     }

    @Override
    public User selectByUserName(String username) {
        //非空校验
        if(!StringUtils.hasLength(username)){
            //为空
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //返回查询结果
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        //1.非空校验
        if(!StringUtils.hasLength(username) ||
        !StringUtils.hasLength(password)){
            //输入不合法
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //2.按照用户名查找用户信息
        User user = selectByUserName(username);

        //3.对查询用户的信息进行校验
        if(user == null){
            //查询出来的信息不合法
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString() + "username = " + username);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        //4.对我们存入的密码进行加密操作
        String str = MD5Util.md5_salt(password, user.getSalt());

        //5.对密文和数据库中的密文进行校验
        if(!str.equalsIgnoreCase(user.getPassword())){
            //不相等
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString() + "密码错误 username = " + username);
            //抛出异常(两次密码不一致)
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //打印登录成功的日志
        log.warn("登录成功,username = " + username);
        //登录成功，返回用户信息
        return user;
    }

    @Override
    public User selectById(Long id) {
        //1.非空校验
        if(!StringUtils.hasLength(String.valueOf(id))){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.调用DAO查询数据库并获取对象
        User user = userMapper.selectByPrimaryKey(id);
        //3.返回结果
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }

        //2.查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null){
            //1.打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString() + "user id:" + id);
            //2.抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //3.更新帖子数量
        //创建要更改的对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);
        //调用动态更新的方法,更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.FAILED.toString() + "，受影响的行数不等于1。");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        //校验参数
        if(id == null || id <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据板块id查询板块的信息
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null || user.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //构建要修改的数据
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() - 1);
        //判断-1之后的发帖数字是不是小于0
        if(updateUser.getArticleCount() < 0){
            //设置为0
            updateUser.setArticleCount(0);
        }
        updateUser.setUpdateTime(new Date());

        //调用Dao层,更新数据库
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString() + "受影响的行数不等于1");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyInfo(User user) {
        //1.非空校验
        if(user == null ||user.getId() == null || user.getId() <= 0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.校验用户是否存在
        User existsUser = userMapper.selectByPrimaryKey(user.getId());
        if(existsUser == null ){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //3.定义一个标志位用于处理所有的信息都未填写的情况
        boolean checkAttr = false; //false表示没有校验通过

        //4.定义一个专门用来更新的对象，防止后面修改的时候传入的参数过多设置了其他的属性(未校验)
        User updateUser = new User();
        //5.设置用户id
        updateUser.setId(user.getId());
        //对每个参数进行校验
        //6.校验用户名
        if(!StringUtil.isEmpty(user.getUsername()) &&
                !existsUser.getUsername().equals(user.getUsername())){
            //需要更新用户是进行唯一性的校验
            //查询设置的用户名是否存在
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if(checkUser != null){
                //用户已经存在
                //打印日志
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                //抛出异常
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            //用户名不存在
            updateUser.setUsername(user.getUsername());
            //更新标志位
            checkAttr = true;
        }
        //7.校验昵称
        if(!StringUtil.isEmpty(user.getNickname()) &&
                !existsUser.getNickname().equals(user.getNickname())){
            updateUser.setNickname(user.getNickname());
            //更新标志位
            checkAttr = true;
        }
        //8.校验性别
        if(user.getGender() != null &&
                user.getGender() != existsUser.getGender()){
            //设置性别
            updateUser.setGender(user.getGender());
            //判断设置的参数
            if(updateUser.getGender() > 2 || updateUser.getGender() < 0){
                updateUser.setGender((byte)2);
            }
            //更新标志位
            checkAttr = true;
        }
        //9.校验邮箱
        if(user.getEmail() != null &&
                user.getEmail() != existsUser.getEmail()){
            //设置邮箱
            updateUser.setEmail(user.getEmail());
            //更新标志位
            checkAttr = true;
        }
        //10.校验电话号码
        if(user.getPhoneNum() != null &&
                user.getPhoneNum() != existsUser.getPhoneNum()){
            //设置号码
            updateUser.setPhoneNum(user.getPhoneNum());
            //更新标志位
            checkAttr = true;
        }
        //11.校验个人简介
        if(user.getRemark() != null &&
                user.getRemark() != existsUser.getRemark()){
            //设置个人简介
            updateUser.setRemark(user.getRemark());
            //更新标志位
            checkAttr = true;
        }
        //12.判断标志位
        if(checkAttr == false){
            //未发生修改,不可更新
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //13.调用DAO
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        //非空校验
        if(id == null || id <= 0 || !StringUtils.hasLength(newPassword) || !StringUtils.hasLength(oldPassword)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据用户id获取用户信息
        User user = userMapper.selectByPrimaryKey(id);
        //判断用户是否存在
        if(user == null || user.getDeleteState() == 1){
            //用户不存在
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //判断旧密码是否正确
        //对老密码进行加密，获取密文
        String oldString = MD5Util.md5_salt(oldPassword, user.getSalt());
        if(!oldString.equalsIgnoreCase(user.getPassword())){
            //密码不正确
            //打印日志
            log.warn(ResultCode.FAILED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed("原始密码不正确，请重新输入"));
        }
        //原始密码正确
        //生成新密码的盐值
        String salt = UUIDUtil.UUID_32();
        //生成新密码的密文
        String encryptPassword = MD5Util.md5_salt(newPassword,salt);
        //构造要更新的数据
        User updateUser = new User();
        updateUser.setId(user.getId()); //用户的id
        updateUser.setSalt(salt); //新生成的盐
        updateUser.setPassword(encryptPassword); //新生成的密码对应的密文
        updateUser.setUpdateTime(new Date()); //设置更新时间
        //调用DAO
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            //打印日志
            log.warn(ResultCode.FAILED.toString() + "，受影响的行数不等于 1。");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }


}
